const miniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");
const { merge } = require("webpack-merge");
const baseConfig = require("./webpack.base.config");
const optimizeCss = require("optimize-css-assets-webpack-plugin");
const purifyCss = require("purifycss-webpack");
const glob = require("glob-all"); // 方便匹配和取路径的一个库
const TenserWebpackPlugin = require("terser-webpack-plugin");

const prodConfig = {
  output: {
    path: path.resolve(__dirname, "./build"),
    filename: "[name]-[chunkhash:6].js",
  },
  mode: "production",
  module: {
    rules: [
      {
        test: /\.less$/,
        include: path.resolve(__dirname, "./src"),
        use: [
          miniCssExtractPlugin.loader,
          "css-loader",
          "postcss-loader",
          "less-loader",
        ],
      },
    ],
  },
  optimization: {
    minimizer: [
      new TenserWebpackPlugin({
        terserOptions: {
          compress: {
            pure_funcs: ["console.log"], // 去除console.log
          },
        },
      }),
    ], // 使用 terser-webpack-plugin 压缩工具
  },
  plugins: [
    new optimizeCss({
      // 使用 cssnano 做引擎 实现压缩css
      cssprocessor: require("cssnano"),
    }),
    new miniCssExtractPlugin({
      filename: "css/[name].css", // [name]是根据入口的占位符生成的
    }),
    new purifyCss({
      // 需要做tree-shaking的文件路径
      paths: glob.sync([
        // .js文件和.html文件有可能会引用css 所以要加上匹配路径
        path.resolve(__dirname, "./src/*.js"),
        path.resolve(__dirname, "./src/*.html"),
      ]),
    }),
  ],
};

module.exports = merge(baseConfig, prodConfig);
